package com.example.shcenterpid.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shcenterpid.Adapter.AgeAdapter;
import com.example.shcenterpid.Adapter.AutoLocateHorizontalView;
import com.example.shcenterpid.Adapter.TicketShowAdapter;
import com.example.shcenterpid.Bean.TicketResultBean;
import com.example.shcenterpid.Custom.GridLayout;
import com.example.shcenterpid.Help.Customer;
import com.example.shcenterpid.Help.LogUtil;
import com.example.shcenterpid.Help.SPUtils;
import com.example.shcenterpid.Help.ThreadManager;
import com.example.shcenterpid.Help.ToastUtil;
import com.example.shcenterpid.Help.httpUtils;
import com.example.shcenterpid.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<String> ageList;
    private AgeAdapter ageAdapter;
    private GridView mGlShow;
    private List<TicketResultBean.DataBean.TimeControlListBean> dataList;
    private List<TicketResultBean.DataBean> dataListAll;
    TicketResultBean ticketResultBean;
    private TicketShowAdapter adapter;
    private TextView mDate;
    private ImageView mSetting;
    private LinearLayout llSetting;
    private Button btIp;
    private EditText etIp;
    private String BaseIp;
    private int showPos;
    private AutoLocateHorizontalView AutoView;
    //在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    CharSequence sysTimeStr = DateFormat.format("yyyy-MM-dd", sysTime);//时间显示格式
                    SPUtils.put(MainActivity.this, Customer.TODAY_DATA, sysTimeStr);
                    initDate();
                    mDate.setText(sysTimeStr);
                    break;
                default:
                    break;

            }
        }
    };
    private TimeThread timeThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideStatusBar();
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        timeThread = new TimeThread();
        timeThread.start();
        initView();
        initDate();
        doThing();
    }

    private void doThing() {
        mSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etIp.setText(BaseIp);
                if (mGlShow.isShown()) {
                    mGlShow.setVisibility(View.GONE);
                } else {
                    mGlShow.setVisibility(View.VISIBLE);
                }

                if (llSetting.isShown()) {
                    llSetting.setVisibility(View.GONE);
                } else {
                    llSetting.setVisibility(View.VISIBLE);
                }

                if (mGlShow.isShown()) {
                    llSetting.setVisibility(View.GONE);
                }
            }
        });

        btIp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!etIp.getText().toString().trim().isEmpty()) {
                    //输入框不为空，那么就保存
                    BaseIp = etIp.getText().toString().trim();
                    SPUtils.put(MainActivity.this, Customer.BASE_IP, BaseIp);
                }
                hideInput();
                mGlShow.setVisibility(View.VISIBLE);
                llSetting.setVisibility(View.GONE);
            }
        });
    }

    private void initDate() {
        if (BaseIp == null || BaseIp.equals("")) {
            ToastUtil.showToast("请先点击左上角按钮，配置地址");
            return;
        }

//        BaseIp = "http://192.168.20.198:8010/Base";
        //第一次获取数据
        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                JSONObject param = new JSONObject();
                try {
                    param.put("orderArrivalDate", (String) SPUtils.get(MainActivity.this, Customer.TODAY_DATA, ""));
//                    param.put("orderArrivalDate", "2020-03-10");
                    String ss = httpUtils.postJson(BaseIp + Customer.GET_LEFT_TICKET, param);
                    try {
                        ticketResultBean = new Gson().fromJson(ss, TicketResultBean.class);
                        dataList.clear();
                        ageList.clear();
                        ageList.add("正在初始化");
                        for (int i = 0; i < ticketResultBean.getData().size(); i++) {
                            for (int i1 = 0; i1 < ticketResultBean.getData().get(i).getTimeControlList().size(); i1++) {
                                // 这个是对标题的整理
                                if (!ageList.contains(ticketResultBean.getData().get(i).getTimeControlList().get(i1).getScenicSpotsName())) {
                                    ageList.add(ticketResultBean.getData().get(i).getTimeControlList().get(i1).getScenicSpotsName());
                                }
                            }
                            dataListAll.add(ticketResultBean.getData().get(i));
                        }
                        if (dataListAll != null && dataListAll.size() > 0) {
                            for (TicketResultBean.DataBean.TimeControlListBean timeControlListBean : dataListAll.get(showPos).getTimeControlList()) {
                                    dataList.add(timeControlListBean);
                            }
                        }
                        if (ageList.size() > 1) {
                            ageList.remove("正在初始化");
                        } else {
                            ageList.remove("正在初始化");
                            ageList.add("没有查询到数据");
                        }
                    } catch (Exception e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("网络请求异常，请确保网络环境");
                            }
                        });
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("网络请求异常，请确保网络环境");
                        }
                    });
                }
            }
        });
        adapter.notifyDataSetChanged();
        ageAdapter.notifyDataSetChanged();
    }

    private void initView() {
        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        if (dataListAll == null) {
            dataListAll = new ArrayList<>();
        }
        AutoView = (AutoLocateHorizontalView) findViewById(R.id.recyleview);
        mDate = (TextView) findViewById(R.id.tv_data);
        mGlShow = (GridView) findViewById(R.id.tv_show);
        mSetting = (ImageView) findViewById(R.id.iv_setting);
        llSetting = (LinearLayout) findViewById(R.id.ll_setting);
        btIp = (Button) findViewById(R.id.bt_ip_ok);
        etIp = (EditText) findViewById(R.id.et_ip);
        llSetting.setVisibility(View.GONE);
        mGlShow.setVisibility(View.VISIBLE);
        adapter = new TicketShowAdapter(this, dataList);
        mGlShow.setAdapter(adapter);

        BaseIp = (String) SPUtils.get(MainActivity.this, Customer.BASE_IP, "");
        mDate.setText((String) SPUtils.get(MainActivity.this, Customer.TODAY_DATA, ""));


        // 测试数据===================================
        showPos = 0;
        ageList = new ArrayList<>();
        ageList.add("正在初始化");
        ageAdapter = new AgeAdapter(this, ageList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        AutoView.setLayoutManager(linearLayoutManager);
        AutoView.setOnSelectedPositionChangedListener(new AutoLocateHorizontalView.OnSelectedPositionChangedListener() {
            @Override
            public void selectedPositionChanged(int pos) {
                //根据返回的数据位置，然后对数据进行显示
                showPos = pos;
                dataList.clear();
                if (dataListAll != null && dataListAll.size() > 0) {
                    for (TicketResultBean.DataBean.TimeControlListBean timeControlListBean : dataListAll.get(showPos).getTimeControlList()) {
                        dataList.add(timeControlListBean);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });

        AutoView.setAdapter(ageAdapter);

    }

    private void hideStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }


    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(5000);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔5秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (timeThread == null) {
            timeThread = new TimeThread();
            timeThread.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        timeThread.interrupt();
        timeThread = null;
    }

}

